import time
from datetime import datetime
import os
from pathlib import Path
import psutil
import schedule

LOG_FILE = "pyWatcher.log"
TARGET = "PalServer.exe" 
TIMER = 180
ACTION = "E:\Game\Steamcmd\steamapps\common\PalServerController\_start.bat"


def main() -> bool:
    pids: list[int] = psutil.pids()
    # process_names: list[str] = []
    for pid in pids:
        p = psutil.Process(pid)
        if p.name() == TARGET:
            mylog(f"[INFO] Target process still alive")
            return True
        else:
            continue
    #  遍历过后仍未找到匹配的pname，尝试重试启动
    mylog(f"[INFO] Target process died, executing action...")
    mylog(f"[INFO] Executed: start cmd /c {ACTION}")
    os.system("start cmd /c " + ACTION)
    return False


def mylog(s: str = ""):
    s = f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}]" + s
    print(s)
    with open(LOG_FILE, "a", encoding="utf-8") as f:
        f.write(s + "\n")
        f.close()


if __name__ == "__main__":
    os.system("title pyWatcher")
    if not os.path.exists(LOG_FILE):
        Path(LOG_FILE).touch()
    schedule.run_pending()
    schedule.every(TIMER).minutes.do(main)
    mylog(f"[Init] Program will check {TARGET} if is alive every {TIMER} minutes")

    while True:
        schedule.run_pending()
        time.sleep(1)
